package com.mingmen.canting.chushizhang;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.flycotablelayout.flyco.tablayout.SlidingTabLayout;
import com.mingmen.canting.flycotablelayout.flyco.tablayout.listener.OnTabSelectListener;
import com.mingmen.canting.flycotablelayout.flyco.tablayout.widget.MsgView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.http.callback.StringNoCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ViewFindUtils;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ChuShiZhangCaiGouDanActivity extends AppCompatActivity implements OnTabSelectListener {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    private Context mContext = this;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private final String[] mTitles = {
            "订单审核", "查看采购单", "采购入库单"
    };
    private MyPagerAdapter mAdapter;
    String token;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            initcrateData();
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chushi_caigou);
        ButterKnife.bind(this);
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        token = (String) SharePreferenceUtil.get(this, "token", "");

        lock();
//        mFragments.add(CaiGouShenHeFragment.getInstance(mTitles[0]));
        mFragments.add(CaiGouNewShenHeFragment.getInstance(mTitles[0]));
        mFragments.add(ChaKancaigourfagment.getInstance(mTitles[1]));
        mFragments.add(CaiGouRuKuFagment.getInstance(mTitles[2]));
        imgRight.setVisibility(View.VISIBLE);
        View decorView = getWindow().getDecorView();
        ViewPager vp = ViewFindUtils.find(decorView, R.id.vp);
        mAdapter = new MyPagerAdapter(getSupportFragmentManager());
        vp.setAdapter(mAdapter);
        /**自定义部分属性*/
        SlidingTabLayout tabLayout_2 = ViewFindUtils.find(decorView, R.id.tl_2);
        /** indicator固定宽度 */
        tabLayout_2.setViewPager(vp);
        tabLayout_2.setOnTabSelectListener(this);
        textCenter.setText("采购单");
        vp.setCurrentItem(0);

        MsgView rtv_2_3 = tabLayout_2.getMsgView(2);

        if (rtv_2_3 != null) {

            rtv_2_3.setBackgroundColor(Color.parseColor("#E84343"));
        }

        vp.setOffscreenPageLimit(0);
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d("viewpager", position + "");
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        initcrateData();

        //开始执行


    }

    public void lock() {
        HttpResponse.setLock(token, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("SUoDIngZhwenban", s);
                Log.d("对砧板上锁", s);
            }
        });
    }

    @Override
    public void onTabSelect(int position) {
//        Toast.makeText(ChuShiZhangCaiGouDanActivity.this, position + "", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onTabReselect(int position) {
//        Toast.makeText(ChuShiZhangCaiGouDanActivity.this, position + "", Toast.LENGTH_LONG).show();
    }

    @OnClick({R.id.text_return, R.id.text_center, R.id.img_right, R.id.tv_right, R.id.linear_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.linear_return:
            case R.id.text_return:
                service.shutdownNow(); //取消
                getunLock();
//                finish();
                break;
            case R.id.text_center:
                break;
            case R.id.img_right:
                break;
            case R.id.tv_right:
                break;
        }
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    public void initcrateData() {
        HttpResponse.setHeartBeat(token, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("initcrateData", s);
                Log.d("initcrateData", "执行心跳");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
    ScheduledExecutorService service;
    @Override
    protected void onResume() {
        Runnable runnable = new Runnable() {
            //创建 run 方法
            public void run() {
                // task to run goes here
                initcrateData();
            }
        };
        // ScheduledExecutorService:是从Java SE5的java.util.concurrent里，
        // 做为并发工具类被引进的，这是最理想的定时任务实现方式。
          service = Executors
                .newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        // 10：秒   5：秒
        // 第一次执行的时间为10秒，然后每隔五秒执行一次
        service.scheduleAtFixedRate(runnable, 10, 60, TimeUnit.SECONDS);

//        timer.schedule(task, 0, 1000 * 60 * 3);
        super.onResume();
    }

    public void getunLock() {
        HttpResponse.setUnLock(token, new StringNoCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("onDestroy", s);
                Log.d("onDestroy", "取消心跳");
//                timer.cancel();
                finish();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                finish();
                super.onError(call, response, e);
            }
        });
    }


}
